package org.aiforum.backend.service;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import org.aiforum.backend.common.QueryPreperty;
import org.aiforum.backend.common.Response;
import org.aiforum.backend.mapper.UserMapper;
import org.aiforum.domain.User;
import org.aiforum.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;

@Service("userService")
@Transactional(TxType.REQUIRED)
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public Response insert(User user) {
		//初始化用户对象
		user.setState(1);
		user.setCreateDate(new Date());
		user.setPassword(MD5Util.encryptMD5(user.getPassword()));
		//插入对象
		userMapper.insert(user);
		Response response=Response.getInstaner();
		response.setState(true);
		response.setMessage("Add success");
		return response;
	}

	@Override
	public Response update(User user) {
		//初始化用户对象
		user.setState(1);
		//插入对象
		userMapper.update(user);
		Response response=Response.getInstaner();
		response.setState(true);
		response.setMessage("Update success");
		return response;
	}

	@Override
	public User find(int userId) {
		User user=userMapper.findById(userId);
		return user;
	}

	@Override
	public Response delete(int userId) {
		userMapper.delete(userId);
		Response response=Response.getInstaner();
		response.setState(true);
		response.setMessage("Delete success");
		return response;
	}

	@Override
	public List<User> queryByPreperty(QueryPreperty queryPreperty) {
		//检验属性值
		if(StringUtil.isNotEmpty(queryPreperty.getQueryValue().toString())){
			//构建模糊查询语句
			String value="%"+queryPreperty.getQueryValue()+"%";
			queryPreperty.setQueryValue(value);
		}else{
			queryPreperty.setQueryValue(null);
		}
		return userMapper.queryByPreperty(queryPreperty);
	}

	@Override
	public Response checkExists(QueryPreperty queryPreperty) {
		int count=userMapper.checkExists(queryPreperty);
		Response response=Response.getInstaner();
		if(count>0){
			response.setState(true);
			response.setMessage(queryPreperty.getQueryName()+"already exists");
		}
		return response;
	}

}
